from django.http import JsonResponse, HttpRequest
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
import json
import os

from .services.bilibili_summary import BilibiliVideoSummarizer


def _get_request_json(request: HttpRequest) -> dict:
    try:
        return json.loads(request.body.decode('utf-8')) if request.body else {}
    except Exception:
        return {}


def _get_summarizer() -> BilibiliVideoSummarizer:
    return BilibiliVideoSummarizer(
        deepseek_api_key=getattr(settings, 'DEEPSEEK_API_KEY', ''),
        aliyun_access_key=getattr(settings, 'ALIYUN_ACCESS_KEY', ''),
        aliyun_secret_key=getattr(settings, 'ALIYUN_SECRET_KEY', ''),
        aliyun_app_key=getattr(settings, 'ALIYUN_APP_KEY', ''),
    )


@csrf_exempt
def bilibili_extract(request: HttpRequest):
    """API合集-子功能：提取B站视频

    支持两种模式：
    - 仅获取真实视频URL（默认）
    - download=true 时执行下载，返回保存路径
    """
    if request.method not in ('GET', 'POST'):
        return JsonResponse({'code': 405, 'msg': 'method not allowed'}, status=405)

    data = _get_request_json(request) if request.method == 'POST' else request.GET
    bv_id = data.get('bv_id') or data.get('bv') or ''
    download_flag = str(data.get('download', 'false')).lower() in ('1', 'true', 'yes')
    output_dir = data.get('output_dir') or os.path.join(settings.MEDIA_ROOT, 'bilibili')

    if not bv_id or not bv_id.startswith('BV'):
        return JsonResponse({'code': 400, 'msg': '缺少或非法的bv_id，示例：BV1xx411c7mD'}, status=400)

    try:
        summarizer = _get_summarizer()
        video_url = summarizer.get_video_url(bv_id)

        if not download_flag:
            return JsonResponse({'code': 0, 'data': {'bv_id': bv_id, 'video_url': video_url}})

        video_file, subtitle_file = summarizer.download_video_with_ytdlp(bv_id, output_dir)
        return JsonResponse({
            'code': 0,
            'data': {
                'bv_id': bv_id,
                'video_url': video_url,
                'video_file': video_file,
                'subtitle_file': subtitle_file,
            }
        })
    except Exception as exc:
        return JsonResponse({'code': 500, 'msg': f'{exc}'}, status=500)


@csrf_exempt
def bilibili_summarize(request: HttpRequest):
    """API合集-子功能：生成视频总结（同步处理）。"""
    if request.method not in ('GET', 'POST'):
        return JsonResponse({'code': 405, 'msg': 'method not allowed'}, status=405)

    data = _get_request_json(request) if request.method == 'POST' else request.GET
    bv_id = data.get('bv_id') or data.get('bv') or ''
    output_dir = data.get('output_dir') or os.path.join(settings.MEDIA_ROOT, 'bilibili')

    if not bv_id or not bv_id.startswith('BV'):
        return JsonResponse({'code': 400, 'msg': '缺少或非法的bv_id，示例：BV1xx411c7mD'}, status=400)

    try:
        summarizer = _get_summarizer()
        os.makedirs(output_dir, exist_ok=True)
        summary = summarizer.process_video(bv_id, output_dir=output_dir)
        return JsonResponse({'code': 0, 'data': {'bv_id': bv_id, 'summary': summary}})
    except Exception as exc:
        return JsonResponse({'code': 500, 'msg': f'{exc}'}, status=500)


